using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using YooAsset.Editor;

namespace HybridCLR
{
    public static partial class BuildPlayerHelper
    {
        /// <summary>
        /// 获得当前时间的""yyyy-MM-dd HH:mm:ss""格式字符串
        /// </summary>
        static string GetDateTime()
        {
            return DateTime.Now.ToString("yyyyMMddHHmm");
        }

        /// <summary>
        /// 获取打包路径
        /// </summary>
        static string GetPackLocation(string outputPath)
        {
            var activeTarget = EditorUserBuildSettings.activeBuildTarget;
            var buildVersion = AssetBundleBuilderWindow.GetBuildVersion();
            var dataTime = GetDateTime();
            var builder = new StringBuilder(outputPath);
            var suffix = "exe";

            builder.Append($"/FoxucHybridCLR");

            switch (activeTarget)
            {
                case BuildTarget.Android:
                    suffix = "apk";
                    builder.Append($"_v{buildVersion}_{dataTime}");
                    break;
                default:
                    break;
            }
            
            builder.Append($".{suffix}");
            return builder.ToString();
        }

        /// <summary>
        /// 拷贝dll到热更新目录
        /// </summary>
        /// <param name="target"></param>
        public static void CopyAssetBundles(BuildTarget target)
        {
            string tempDir = BuildConfig.GetAssetBundleResourcesHotAssemblyDir();
            string hotfixDllSrcDir = BuildConfig.GetHotUpdateDllsOutputDirByTarget(target);

            if (!Directory.Exists(tempDir))
                Directory.CreateDirectory(tempDir);

            foreach (var dll in BuildConfig.AllHotUpdateDllNames)
            {
                string dllPath = $"{hotfixDllSrcDir}/{dll}";
                string dllBytesPath = $"{tempDir}/{dll}.bytes";
                File.Copy(dllPath, dllBytesPath, true);
            }

            string aotDllDir = BuildConfig.GetAssembliesPostIl2CppStripDir(target);
            foreach (var dll in BuildConfig.AOTMetaDlls)
            {
                string dllPath = $"{aotDllDir}/{dll}";
                if (!File.Exists(dllPath))
                {
                    Debug.LogError($"ab中添加AOT补充元数据dll:{dllPath} 时发生错误,文件不存在。裁剪后的AOT dll在BuildPlayer时才能生成，因此需要你先构建一次游戏App后再打包。");
                    continue;
                }
                string dllBytesPath = $"{tempDir}/{dll}.bytes";
                File.Copy(dllPath, dllBytesPath, true);
            }
        }
    }
}
